import Sanke from './Snake';
import Food from './Food';
import scorePanel from './scorePanel';
class GameControl {
    snake = new Sanke
    food = new Food
    scorePanel = new scorePanel
    direction: string = ''
    isLive = true
    constructor() {
        this.init()
    }
    init() {
        document.addEventListener("keydown", this.keyDownHandler.bind(this))
        this.run()
    }
    keyDownHandler(event: KeyboardEvent) {
        console.log(event.key)
        this.direction = event.key
    }
    run() {
        let X = this.snake.X
        let Y = this.snake.Y
        switch (this.direction) {
            case 'ArrowUp':
                Y -=10
                break
            case 'ArrowDown':
                Y +=10
                break
            case 'ArrowLeft':
                X -=10
                break
            case 'ArrowRight':
                X +=10
                break
        }
        this.checkEat(X,Y)
        try{
            this.snake.X = X
            this.snake.Y = Y
        }catch(e:any){
            alert(e.message+'GAME OVER!!!')
            this.isLive = false
        }

        this.isLive && setTimeout(this.run.bind(this) , 300 - (this.scorePanel.level -1)*30)
    }
    checkEat(X:number,Y:number){
        if(X === this.food.X && Y === this.food.Y){
            this.food.change()
            this.scorePanel.addScore()
            this.snake.addBody()
        }
    }

}
export default GameControl